import React, { useEffect, useRef, useState } from 'react';

interface SlideEditorProps {
  value: string | undefined;
  onChange: (content: string) => void;
}

// Reveal.js 动态加载 + 文本编辑双栏；加载失败自动降级为仅文本编辑
const SlideEditor: React.FC<SlideEditorProps> = ({ value, onChange }) => {
  const [text, setText] = useState<string>(() => value || '# 幻灯片标题\n\n---\n\n## 第二页');
  const [revealReady, setRevealReady] = useState(false);
  const deckRef = useRef<{ Reveal: unknown; Markdown: unknown } | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    setText(value || '');
  }, [value]);

  // 动态加载 reveal.js 与样式（使用 CDN，避免本地未安装依赖时报错）
  useEffect(() => {
    let canceled = false;
    (async () => {
      try {
        // 注入样式（CDN）
        const ensureLink = (href: string) => {
          if (document.querySelector(`link[href="${href}"]`)) return;
          const link = document.createElement('link');
          link.rel = 'stylesheet';
          link.href = href;
          document.head.appendChild(link);
        };
        ensureLink('https://cdn.jsdelivr.net/npm/reveal.js@5/dist/reveal.css');
        ensureLink('https://cdn.jsdelivr.net/npm/reveal.js@5/dist/theme/black.css');

        // 通过远程 ESM 加载（避免构建时解析 bare import）
        // @vite-ignore
        const Reveal = await import(/* @vite-ignore */ 'https://cdn.jsdelivr.net/npm/reveal.js@5/dist/reveal.esm.js').catch(() => null);
        // @vite-ignore
        const markdown = await import(/* @vite-ignore */ 'https://cdn.jsdelivr.net/npm/reveal.js@5/plugin/markdown/markdown.esm.js').catch(() => null);
        if (!Reveal || !markdown || canceled) return;
        deckRef.current = { 
          Reveal: (Reveal as { default?: unknown } & unknown).default || Reveal, 
          Markdown: (markdown as { default?: unknown } & unknown).default || markdown 
        };
        setRevealReady(true);
      } catch {
        setRevealReady(false);
      }
    })();
    return () => { canceled = true; };
  }, []);

  // 当 ready 或文本改变时渲染/重建 deck
  useEffect(() => {
    if (!revealReady || !containerRef.current || !deckRef.current) return;
    const { Reveal, Markdown } = deckRef.current;
    // 清空容器并构建 markdown sections
    containerRef.current.innerHTML = '';
    const deckEl = document.createElement('div');
    deckEl.className = 'reveal';
    const slidesEl = document.createElement('div');
    slidesEl.className = 'slides';
    // 使用单个 section + data-markdown 由插件解析（支持 --- 分页）
    const section = document.createElement('section');
    section.setAttribute('data-markdown', '');
    const script = document.createElement('script');
    script.type = 'text/template';
    script.text = text || '# 空白页';
    section.appendChild(script);
    slidesEl.appendChild(section);
    deckEl.appendChild(slidesEl);
    containerRef.current.appendChild(deckEl);

    const deck = new Reveal(deckEl, {
      hash: false,
      plugins: [Markdown],
      embedded: true,
      width: '100%',
      height: 480,
      margin: 0.04,
      slideNumber: false,
      transition: 'slide',
    });
    deck.initialize().catch(() => {});

    return () => {
      try { 
        deck.destroy(); 
      } catch {
        // 忽略销毁错误
      }
    };
  }, [revealReady, text]);

  return (
    <div className="space-y-3">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <div>
          <div className="text-sm text-gray-500 mb-1">Markdown 编辑</div>
          <textarea
            className="w-full h-72 p-3 border rounded font-mono text-sm"
            value={text}
            onChange={(e) => {
              setText(e.target.value);
              onChange(e.target.value);
            }}
          />
        </div>
        <div>
          <div className="text-sm text-gray-500 mb-1">
            {revealReady ? '预览（Reveal.js）' : '预览不可用（未安装 reveal.js，使用纯文本编辑）'}
          </div>
          <div ref={containerRef} className="border rounded min-h-[300px] overflow-hidden bg-black/5" />
        </div>
      </div>
    </div>
  );
};

export default SlideEditor;


